package wsz.dao;

import tm.ConnectionUtils;
import wsz.pojo.User;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wsz
 * @date 2021/10/13 13:42
 **/
public class UserDaoImpl implements UserDao {

    private ConnectionUtils connectionUtils;

    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }

    @Override
    public List<User> findAll() throws Exception {

        Connection connection = connectionUtils.getConnection();

        String sql = "select * from user";

        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        ResultSet resultSet = preparedStatement.executeQuery();

        List<User> objects = new ArrayList<>();
        while (resultSet.next()) {
            ResultSetMetaData metaData = resultSet.getMetaData();
            User instance = new User();
            for (int i = 1; i <= metaData.getColumnCount() ; i++) {
                String columnName = metaData.getColumnName(i);
                Object object = resultSet.getObject(columnName);

                // 使用反射/内省，封装，库表与实体类字段的对象
                PropertyDescriptor descriptor = new PropertyDescriptor(columnName, User.class);
                Method writeMethod = descriptor.getWriteMethod();
                writeMethod.invoke(instance, object);
            }
            objects.add(instance);
        }
        return objects;
    }

    @Override
    public int update(User user) throws Exception {
        Connection connection = connectionUtils.getConnection();
        String sql = " update user set name = ?, password =? where id=?";

        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setObject(1, user.getName());
        preparedStatement.setObject(2, user.getPassword());
        preparedStatement.setObject(3, user.getId());

        return preparedStatement.executeUpdate();
    }
}
